import APIS from "@/api";
import CButton from "@/components/Custom/CButton";
import type {
  ActionType,
  ProColumns,
  ProDescriptionsItemProps,
} from "@ant-design/pro-components";
import {
  FooterToolbar,
  PageContainer,
  ProDescriptions,
  ProTable,
} from "@ant-design/pro-components";
import { FormattedMessage, useRequest } from "@umijs/max";
import {
  Button,
  Drawer,
  Image,
  message,
  Popconfirm,
  Popover,
  QRCode,
} from "antd";
import copy from "copy-to-clipboard";
import dayjs from "dayjs";
import React, { useCallback, useRef, useState } from "react";
import CreateForm from "./components/CreateForm";
import downloadHtml from "./downloadHtml";
import downloadImageTable, { downloadImage } from "./downloadImageTable";

// 给body添加点击事件监听
document.body.addEventListener("click", function (e) {
  // 检查触发事件的元素是否包含目标类名
  if (e.target.classList.contains("ant-image-preview-img")) {
    downloadImage(e.target);
  }
});

const TableList: React.FC = () => {
  const actionRef = useRef<ActionType | null>(null);

  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<API.RuleListItem>();
  const [selectedRowsState, setSelectedRows] = useState<API.RuleListItem[]>([]);

  const [messageApi, contextHolder] = message.useMessage();
  const listRef = useRef<any>([]);
  const { run: delRun, loading } = useRequest(() => {}, {
    manual: true,
    onSuccess: () => {
      setSelectedRows([]);
      actionRef.current?.reloadAndRest?.();

      messageApi.success("Deleted successfully and will refresh soon");
    },
    onError: () => {
      messageApi.error("Delete failed, please try again");
    },
  });

  const columns: ProColumns<API.RuleListItem>[] = [
    {
      title: "活动名称",
      dataIndex: "name",
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: "活动日期",
      dataIndex: "timeAt",
      valueType: "dateTimeRange",
      render(dom, record) {
        return `${dayjs(record?.timeAt?.[0]).format(
          "YYYY-MM-DD HH:mm"
        )}~${dayjs(record?.timeAt?.[1]).format("HH:mm")}`;
      },
    },
    {
      title: "星期",
      dataIndex: "weekdayStr",
      valueEnum: "一二三四五六日".split("").reduce((obj, key) => {
        let text = `星期${key}`;
        obj[text] = { text };
        return obj;
      }, {} as any),
    },
    {
      title: "活动链接",
      dataIndex: "link",
      copyable: true,
      width: 200,
      hideInSearch: true,
      render: (dom, record) => {
        return <LinkRender dom={dom} record={record} />;
      },
    },
    {
      title: "报名链接",
      dataIndex: "signLink",
      copyable: true,
      width: 200,
      hideInSearch: true,
    },
    {
      title: "是否可用",
      dataIndex: "enable",
      hideInTable: true,
      hideInSearch: true,
    },

    {
      title: "详细地址",
      tooltip: "活动通知后,确定的地址",
      dataIndex: "address",
      copyable: true,
    },
    {
      title: "活动区域",
      dataIndex: "area",
      copyable: true,
      hideInTable: true,
    },
    {
      title: "不精确地址",
      tooltip: "活动一开始发出时候的地址,标记一个大致范围,比如某个地铁站附近",
      dataIndex: "impreciseAddress",
      copyable: true,
      hideInTable: true,
    },
    {
      title: "主办单位",
      dataIndex: "organizerName",
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: "承办单位",
      dataIndex: "coOrganizerName",
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: "联系方式",
      dataIndex: "contactPeople",
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: "人数",
      dataIndex: "peopleNumber",
      hideInSearch: true,
      hideInTable: true,
    },

    {
      title: "可报名",
      dataIndex: "enableSign",
      hideInTable: true,
      hideInSearch: true,
    },
    {
      title: "描述",
      dataIndex: "desc",
      copyable: true,
      width: 800,
      hideInSearch: true,
      hideInTable: true,
      render(v) {
        return (
          <div
            style={{
              whiteSpace: "pre-wrap",
              lineHeight: 2,
            }}
          >
            {v}
          </div>
        );
      },
    },
    {
      title: "操作",
      dataIndex: "option",
      valueType: "option",
      fixed: "right",
      render(_, record) {
        return (
          <>
            <CreateForm
              key="create"
              reload={actionRef.current?.reload}
              trigger={<Button type={"link"}>编辑</Button>}
              initialValues={record}
            />
            <Popconfirm
              placement="topLeft"
              title={"操作确认"}
              description={"是否删除该数据?"}
              onConfirm={async () => {
                await APIS.activity.remove({
                  id: record._id,
                });
                message.success("删除成功");
                actionRef.current?.reload();
              }}
            >
              <CButton type={"link"} danger>
                删除
              </CButton>
            </Popconfirm>
          </>
        );
      },
    },
  ];

  const handleRemove = useCallback(
    async (selectedRows: API.RuleListItem[]) => {
      if (!selectedRows?.length) {
        messageApi.warning("请选择删除项");
        return;
      }
    },
    [delRun, messageApi.warning]
  );

  return (
    <PageContainer>
      {contextHolder}

      <ProTable<API.RuleListItem, any>
        actionRef={actionRef}
        rowKey="_id"
        scroll={{
          x: "max-content",
        }}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <CButton
            key="xxxx"
            onClick={async () => {
              downloadImageTable(listRef.current);
            }}
          >
            下载图片
          </CButton>,
          <CButton
            key={"23423"}
            onClick={async () => {
              downloadHtml(listRef.current);
            }}
          >
            下载活动信息
          </CButton>,
          <CButton
            key={"234234df"}
            onClick={async () => {
              let res = await APIS.activity.copy();
              copy(res);
              message.success("复制成功");
            }}
          >
            复制活动信息
          </CButton>,
          <CreateForm
            key="create"
            reload={async () => actionRef.current?.reload()}
          />,
        ]}
        onDataSourceChange={(data) => {
          console.log("--->246:", data);
          listRef.current = data;
        }}
        request={async (req) => {
          let res = await APIS.activity.list(req);
          return {
            data: res || [],
            success: true,
            total: res.length,
          };
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              <FormattedMessage
                id="pages.searchTable.chosen"
                defaultMessage="Chosen"
              />{" "}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{" "}
              <FormattedMessage
                id="pages.searchTable.item"
                defaultMessage="项"
              />
              &nbsp;&nbsp;
              <span>
                <FormattedMessage
                  id="pages.searchTable.totalServiceCalls"
                  defaultMessage="Total number of service calls"
                />{" "}
                {selectedRowsState.reduce(
                  (pre, item) => pre + (item.callNo ?? 0),
                  0
                )}{" "}
                <FormattedMessage
                  id="pages.searchTable.tenThousand"
                  defaultMessage="万"
                />
              </span>
            </div>
          }
        >
          <Button
            loading={loading}
            onClick={() => {
              handleRemove(selectedRowsState);
            }}
          >
            <FormattedMessage
              id="pages.searchTable.batchDeletion"
              defaultMessage="Batch deletion"
            />
          </Button>
          <Button type="primary">
            <FormattedMessage
              id="pages.searchTable.batchApproval"
              defaultMessage="Batch approval"
            />
          </Button>
        </FooterToolbar>
      )}

      <Drawer
        width={"80%"}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<API.RuleListItem>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<API.RuleListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

const LinkRender = function ({ dom, record }: any) {
  console.log("--->380:", dom, record);
  let ref = useRef(null);

  let link = record.link || "";
  let isImg = link.endsWith(".png") || link.endsWith(".jpg");
  let httpLink = `https://assesstest.kafamily.cn/img?l=${link}`;
  if (link.startsWith("#小程序")) {
    return dom;
  }
  return (
    <Popover
      content={
        <div>
          <div
            ref={ref}
            style={{
              padding: 10,
              width: 280,
              display: "flex",
              flexDirection: "column",
              alignItems: "center",
              lineHeight: 1.2,
            }}
            onClick={(e) => {
              downloadImage(ref.current as any);
            }}
          >
            <QRCode value={isImg ? httpLink : link} />
            <div style={{ marginTop: 10 }}>{record.name}</div>
            <div>
              时间:{" "}
              {`${dayjs(record?.timeAt?.[0]).format(
                "YYYY-MM-DD HH:mm"
              )}~${dayjs(record?.timeAt?.[1]).format("HH:mm")} ${
                record.weekdayStr
              }`}
            </div>

            <div>地址: {record.address}</div>
          </div>
          {!isImg && (
            <a
              href={link}
              target={"_blank"}
              style={{ display: "block", textAlign: "center" }}
            >
              打开链接
            </a>
          )}
        </div>
      }
    >
      {isImg ? (
        <Image src={link} style={{ width: "100px", maxHeight: "100%" }} />
      ) : (
        dom
      )}
    </Popover>
  );
};
export default TableList;
